package com.etc.zmall.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etc.util.PageData;
import com.etc.zmall.entity.Goods;
import com.etc.zmall.service.GoodsService;
import com.etc.zmall.service.impl.GoodsServiceImpl;

/**
 * Servlet implementation class UserIndexServlet
 */
@WebServlet("/UserIndexServlet")
public class UserIndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserIndexServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1设置请求编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		if ("showByPage".equals(op)) {
			showGoodsByPage(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	private void showGoodsByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		GoodsService gs = new GoodsServiceImpl();
		// 查询全部
		int page = 1;
		int pageSize = 8;
		String keywords = "";
		// 页码和关键字
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		// 传递查询到的商品信息
		PageData<Goods> pd = gs.showGoods(page, pageSize, keywords);
		List<Goods> list1 = pd.getList();
		List<Goods> shopname = new ArrayList<Goods>();
		for (Goods goods : list1) {
			// 调用方法通过商品名称找到店铺名称
			String sn = goods.getGoodsname();
			// 将查到的数据加入数组
			shopname.add(gs.selShopName(goods, sn));
		}
		System.out.println("pd---"+pd.getList());
		request.setAttribute("pd", pd);
		request.setAttribute("shopname", shopname);
		request.setAttribute("keyword", keywords);
		request.getRequestDispatcher("efront/UserIndex.jsp").forward(request, response);
	}
}
